// 获取画布和上下文
const canvas = document.getElementById('game-canvas');
const ctx = canvas.getContext('2d');

// 画布尺寸
const CANVAS_WIDTH = 800;
const CANVAS_HEIGHT = 600;
canvas.width = CANVAS_WIDTH;
canvas.height = CANVAS_HEIGHT;

// 得分
let score = 0;
const scoreElement = document.getElementById('score');

// 篮球属性
const BALL_RADIUS = 20;
let ballX = CANVAS_WIDTH / 2;
let ballY = CANVAS_HEIGHT - BALL_RADIUS;
let ballDx = 0;
let ballDy = 0;
const GRAVITY = 0.2;
const BOUNCE = 0.7;

// 篮筐属性
const HOOP_WIDTH = 80;
const HOOP_HEIGHT = 10;
const HOOP_X = CANVAS_WIDTH / 2 - HOOP_WIDTH / 2;
const HOOP_Y = 100;

// 绘制篮球
function drawBall() {
    ctx.beginPath();
    ctx.arc(ballX, ballY, BALL_RADIUS, 0, Math.PI * 2);
    ctx.fillStyle = 'orange';
    ctx.fill();
    ctx.closePath();
}

// 绘制篮筐
function drawHoop() {
    ctx.beginPath();
    ctx.rect(HOOP_X, HOOP_Y, HOOP_WIDTH, HOOP_HEIGHT);
    ctx.fillStyle = 'red';
    ctx.fill();
    ctx.closePath();
}

// 移动篮球
function moveBall() {
    ballX += ballDx;
    ballY += ballDy;
    ballDy += GRAVITY;

    // 边界检测
    if (ballX - BALL_RADIUS < 0 || ballX + BALL_RADIUS > CANVAS_WIDTH) {
        ballDx = -ballDx;
    }
    if (ballY + BALL_RADIUS > CANVAS_HEIGHT) {
        ballY = CANVAS_HEIGHT - BALL_RADIUS;
        ballDy = -ballDy * BOUNCE;
        if (Math.abs(ballDy) < 0.1) {
            ballDy = 0;
        }
    }

    // 检查是否进球
    if (
        ballX > HOOP_X &&
        ballX < HOOP_X + HOOP_WIDTH &&
        ballY + BALL_RADIUS > HOOP_Y &&
        ballY - BALL_RADIUS < HOOP_Y + HOOP_HEIGHT
    ) {
        score += 2;
        scoreElement.textContent = score;
        // 重置篮球位置
        ballX = CANVAS_WIDTH / 2;
        ballY = CANVAS_HEIGHT - BALL_RADIUS;
        ballDx = 0;
        ballDy = 0;
    }
}

// 处理鼠标点击，投篮
canvas.addEventListener('click', function (event) {
    const rect = canvas.getBoundingClientRect();
    const mouseX = event.clientX - rect.left;
    const mouseY = event.clientY - rect.top;
    const dx = mouseX - ballX;
    const dy = mouseY - ballY;
    const force = 0.1;
    ballDx = dx * force;
    ballDy = dy * force;
});

// 主游戏循环
function gameLoop() {
    ctx.clearRect(0, 0, CANVAS_WIDTH, CANVAS_HEIGHT);

    drawBall();
    drawHoop();
    moveBall();

    requestAnimationFrame(gameLoop);
}

// 初始化游戏
gameLoop();